/**
 * User: 蕨菜
 * Date: 2019-05-22
 * Time: 14:51
 * Description: 此文件简要说明
 */


const sequelize = require('sequelize');

const {
    Class,
    Grade,
    Project,
    Teacher
} = require('../../models');

const {
    AppUtil
} = require('../../util');

module.exports = async function updateClass(body, ctx) {
    const {
        id,
        active,
        year,
        classIds,
        teacherIds,
        projectIds,
    } = body;

    await Grade.update({
        year,
        active
    }, {
        where: {
            id
        }
    });

    const gradeInstance = await Grade.findByPk(id);

    if (AppUtil.isEmpty(classIds)) {
        // 如果classIds为空,那就清空该年级下的所有班级
        await gradeInstance.setClasses([]);
    }

    if (AppUtil.isEmpty(teacherIds)) {
        await gradeInstance.setStudents([]);
    }

    if (AppUtil.isEmpty(projectIds)) {
        await gradeInstance.setProjects([]);
    }

    // -----------分割线 for read better--------------

    if (!AppUtil.isEmpty(classIds)) {
        const classes = await Class.findAll(AppUtil.queryOnlyIn(classIds))
        await gradeInstance.setClasses(classes);
    }

    if (!AppUtil.isEmpty(teacherIds)) {
        const teachers = await Teacher.findAll(AppUtil.queryOnlyIn(teacherIds));
        await gradeInstance.setStudents(teachers);
    }

    if (!AppUtil.isEmpty(projectIds)) {
        const projects = await Project.findAll(AppUtil.queryOnlyIn(projectIds))
        await gradeInstance.setProjects(projects);
    }

    const data = await Grade.findByPk(id);

    return ctx.body = {
        success: true,
        data
    }

}